package com.jh.paymentchannel.service;

import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.BranchNo;
import com.jh.paymentchannel.pojo.JFCoinRegister;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class JFCoinQuickTopupRequest implements TopupRequest{

	private static final Logger log = LoggerFactory.getLogger(JFCoinQuickTopupRequest.class);
	
	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;
	
	@Autowired
	private BranchbankBussiness branchbankBussiness;
	
	@Autowired
	private Util util;
	
	@Value("${payment.ipAddress}")
	private String ipAddress;
	
	@Value("${jfcoin.partnerNo}")
	private String partnerNo;
	
	@Value("${jfcoin.key}")
	private String Key;
	
	
	private static final Charset UTF_8 = StandardCharsets.UTF_8;
	
	@Override
	public Map<String, String> topupRequest(HttpServletRequest request, String amount, String ordercode,
			String orderdesc, String extra, String notifyurl, String returnurl, String channelParam) throws Exception {
		log.info("ipAddress====="+ipAddress);
		log.info("partnerNo====="+partnerNo);
		log.info("Key====="+Key);
		 Map<String, String>  map = new HashMap<String, String>();
		/**首先拿到用户的userid, 如果用户已经存在，那么直接拿用户的sdjuserid, 如果用户的默认结算卡已经和当前不一样了。 需要重新注册 **/
		RestTemplate restTemplate=new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================"+result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		String realamount = resultObj.getString("realAmount");
		String userid = resultObj.getString("userid");
		//通道id
		String channelid = resultObj.getString("channelid");
		//费率
		String rate = resultObj.getString("rate");
		//银行卡
		String bankCard = resultObj.getString("bankcard");

		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================"+result);
		try {
			jsonObject =  JSONObject.fromObject(result);
			resultObj  =  jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}

		if(resultObj.isNullObject()){

			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有结算卡");
			return map;
		}

		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/**身份证号*/
		String idcard   = resultObj.getString("idcard");
		String phone    = resultObj.getString("phone");
		//开户行所在省
		String provinceOfBank = resultObj.getString("province");

		log.info("provinceOfBank"+provinceOfBank);
		//开户行所在市
		String cityOfBank = resultObj.getString("city");

		log.info("cityOfBank"+cityOfBank);
		//银行名称
		String bankName = resultObj.getString("bankName");
		//支行名称
		String bankBranchName = resultObj.getString("bankBranchName");

		/*String expiredTime = resultObj.getString("expiredTime");

		String securityCode = resultObj.getString("securityCode");*/

		String cardType = resultObj.getString("cardType");

		String bankBranchNo;
		try {
			bankBranchNo = branchbankBussiness.getNumByName(bankBranchName);
		} catch (Exception e1) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询支行联行号有误");
			return map;
		}
		log.info("bankBranchNo"+bankBranchNo);

		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================"+result);
		try {
			jsonObject =  JSONObject.fromObject(result);
			resultObj  =  jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if(resultObj==null){
			return null;
		}
		String nature = resultObj.getString("nature"); //卡的类型(借记卡/贷记卡)
		String cardName = resultObj.getString("bankName");

		String expiredTime = "";
		String securityCode = "";

		//有效期
		if(resultObj.containsKey("securityCode")){
			securityCode = resultObj.getString("securityCode");
		}
		//安全码
		if(resultObj.getString("expiredTime")!=null&&!"".equals(resultObj.getString("expiredTime"))){
			expiredTime = resultObj.getString("expiredTime");

			String before = expiredTime.substring(0, 2);
			String after = expiredTime.substring(2, 4);

			BigDecimal big = new BigDecimal(before);
			BigDecimal time = new BigDecimal("12");

			int compareTo = big.compareTo(time);
			//如果前两位大于12，,代表是年/月的格式
			if(compareTo==1){
				expiredTime=after+before;
			}
			log.info("统一格式后的expiredTime========="+expiredTime);
		}


		String cardtype = "1"; //等于1表示贷记卡
		if(nature.contains("借记")){
			cardtype = "0";//等于0表示借记卡
		}

		//随机获取商铺信息表中的商户数据

		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/query/randomuserid";
		requestEntity  = new LinkedMultiValueMap<String, String>();

		String shopUserId;
		try {
			result = restTemplate.postForObject(url, requestEntity, String.class);
			jsonObject =  JSONObject.fromObject(result);
			shopUserId = jsonObject.getString("result");
		} catch (Exception e1) {
			log.error("查询用户ID出错！！！！");
			map.put("resp_code", "failed");
			map.put("channel_type", "sdj");
			map.put("resp_message", "没有查询到用户ID");
			return map;
		}

		log.info("随机获取的userId"+shopUserId);

		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/shops/query/uid";
		requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userid", shopUserId);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================"+result);
		try {
			jsonObject =  JSONObject.fromObject(result);
			resultObj  =  jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询商铺信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询商铺信息有误");
			return map;
		}

		String shopName = resultObj.getString("name");//商户全称

		String address = resultObj.getString("address");// 注册地址
		String shopsAddress = resultObj.getString("shopsaddress");

		String Address = address+shopsAddress;

		String status = resultObj.getString("status");//商铺审核状态

		//根据银行名称查询得到银行信息
		BranchNo findByBankName = branchbankBussiness.findByBankName(bankName);
		//银行总行联行号
		String inBankUnitNo = findByBankName.getBankNo();

		JFCoinRegister jfCoinRegister = topupPayChannelBusiness.getJFCoinRegister(Long.parseLong(userid));

		//将银行名称进行更改
		String bankname = Util.queryBankNameByBranchName(bankName);
		String cardname = Util.queryBankNameByBranchName(cardName);


		if(provinceOfBank==null||"".equals(provinceOfBank)||"null".equals(provinceOfBank)){
			provinceOfBank = "";
		}

		if(cityOfBank==null||"".equals(cityOfBank)||"null".equals(cityOfBank)){
			cityOfBank = "";
		}

		if(bankBranchName==null||"".equals(bankBranchName)||"null".equals(bankBranchName)){
			bankBranchName = "";
		}

		if(bankBranchNo==null||"".equals(bankBranchNo)||"null".equals(bankBranchNo)){
			bankBranchNo = "";
		}


		if(jfCoinRegister == null){
			log.info("用户需要进件========");
			//jfRegister为空表示用户需要进件
			Map maps = new HashMap();
			maps.put("resp_code", "success");
			maps.put("channel_type", "jfcoin");
			maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/tojfcoinbankinfo"+"?bankName="+URLEncoder.encode(bankname,"UTF-8")+"&bankBranchId="+bankBranchNo+
					"&bankNo="+cardNo+"&bankCard="+bankCard+"&cardName="+URLEncoder.encode(cardname,"UTF-8")+"&amount="+amount+"&ordercode="+ordercode+"&provinceOfBank="+URLEncoder.encode(provinceOfBank,"UTF-8")+"&cityOfBank="+URLEncoder.encode(cityOfBank,"UTF-8")+
					"&bankBranchName="+URLEncoder.encode(bankBranchName,"UTF-8")+"&cardType="+URLEncoder.encode(cardType,"UTF-8")+"&isRegister=0"+"&cardtype="+cardtype+"&expiredTime="+expiredTime+"&securityCode="+securityCode);
			return maps;


		}else if(!rate.equals(jfCoinRegister.getRate())){
			//用户费率发生变更，需要重新进件
			log.info("用户费率变更，需要重新进件======");
			Map maps = new HashMap();
			maps.put("resp_code", "success");
			maps.put("channel_type", "jfcoin");
			maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/tojfcoinbankinfo"+"?bankName="+URLEncoder.encode(bankname,"UTF-8")+"&bankBranchId="+bankBranchNo+
					"&bankNo="+cardNo+"&bankCard="+bankCard+"&cardName="+URLEncoder.encode(cardname,"UTF-8")+"&amount="+amount+"&ordercode="+ordercode+"&provinceOfBank="+URLEncoder.encode(provinceOfBank,"UTF-8")+"&cityOfBank="+URLEncoder.encode(cityOfBank,"UTF-8")+
					"&bankBranchName="+URLEncoder.encode(bankBranchName,"UTF-8")+"&cardType="+URLEncoder.encode(cardType,"UTF-8")+"&isRegister=0"+"&cardtype="+cardtype+"&expiredTime="+expiredTime+"&securityCode="+securityCode);
			return maps;


		}else if(topupPayChannelBusiness.getJFCoinRegister(Long.parseLong(userid), cardNo) == null) {
			//用户默认提现卡发生变更，需要重新进件
			log.info("用户默认提现卡变更，需要重新进件=====");
			Map maps = new HashMap();
			maps.put("resp_code", "success");
			maps.put("channel_type", "jfcoin");
			maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/tojfcoinbankinfo"+"?bankName="+URLEncoder.encode(bankname,"UTF-8")+"&bankBranchId="+bankBranchNo+
					"&bankNo="+cardNo+"&bankCard="+bankCard+"&cardName="+URLEncoder.encode(cardname,"UTF-8")+"&amount="+amount+"&ordercode="+ordercode+"&provinceOfBank="+URLEncoder.encode(provinceOfBank,"UTF-8")+"&cityOfBank="+URLEncoder.encode(cityOfBank,"UTF-8")+
					"&bankBranchName="+URLEncoder.encode(bankBranchName,"UTF-8")+"&cardType="+URLEncoder.encode(cardType,"UTF-8")+"&isRegister=0"+"&cardtype="+cardtype+"&expiredTime="+expiredTime+"&securityCode="+securityCode);
			return maps;

		}else{
			log.info("用户进件信息未发生变更，发起交易=======");
			//用户进件信息未发生变更，发起交易
			Map maps = new HashMap();
			maps.put("resp_code", "success");
			maps.put("channel_type", "jfcoin");
			maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/tojfcoinbankinfo"+"?bankName="+URLEncoder.encode(bankname,"UTF-8")+"&bankBranchId="+bankBranchNo+
					"&bankNo="+cardNo+"&bankCard="+bankCard+"&cardName="+URLEncoder.encode(cardname,"UTF-8")+"&amount="+amount+"&ordercode="+ordercode+"&provinceOfBank="+URLEncoder.encode(provinceOfBank,"UTF-8")+"&cityOfBank="+URLEncoder.encode(cityOfBank,"UTF-8")+
					"&bankBranchName="+URLEncoder.encode(bankBranchName,"UTF-8")+"&cardType="+URLEncoder.encode(cardType,"UTF-8")+"&isRegister=1"+"&cardtype="+cardtype+"&expiredTime="+expiredTime+"&securityCode="+securityCode);
			return maps;

		}
	}
	

}
